import { ref, onMounted, watch } from 'vue'

/**
 * @description 主题管理hook
 * @returns {Object} - 返回主题相关的状态和方法
 */
export function useTheme() {
  const isDarkMode = ref(false)

  /**
   * @description 切换主题模式
   */
  const toggleTheme = (event) => {
    isDarkMode.value = !isDarkMode.value
    if (document.startViewTransition) {
      document.documentElement.style.setProperty('--x', event.clientX + 'px')
      document.documentElement.style.setProperty('--y', event.clientY + 'px')
      document.startViewTransition(() => {
        applyTheme()
      });
    } else {
      applyTheme()
    }
  }

  /**
   * @description 应用主题设置
   */
  const applyTheme = () => {
    if (isDarkMode.value) {
      // 设置暗黑模式
      document.documentElement.setAttribute('data-theme', 'dark')
      // 启用Element Plus的暗黑模式 (通过添加dark类)
      document.documentElement.classList.add('dark')
      localStorage.setItem('theme', 'dark')
    } else {
      // 设置亮色模式
      document.documentElement.setAttribute('data-theme', 'light')
      // 禁用Element Plus的暗黑模式 (通过移除dark类)
      document.documentElement.classList.remove('dark')
      localStorage.setItem('theme', 'light')
    }
  }

  /**
   * @description 初始化主题设置
   */
  const initTheme = () => {
    // 优先从本地存储中获取主题设置
    const savedTheme = localStorage.getItem('theme')

    // 如果没有本地设置，则检查系统偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches

    isDarkMode.value = savedTheme === 'dark' || (savedTheme === null && prefersDark)

    applyTheme()
  }

  // 监听系统主题变化
  onMounted(() => {
    initTheme()

    // 监听系统主题变化
    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

    // 使用更新的事件监听方法
    const handleThemeChange = (e) => {
      if (localStorage.getItem('theme') === null) {
        isDarkMode.value = e.matches
        applyTheme()
      }
    }

    // 添加事件监听器
    darkModeMediaQuery.addEventListener('change', handleThemeChange)
  })

  return {
    isDarkMode,
    toggleTheme
  }
} 